import 'package:amap_flutter_map_example/base_page.dart';
import 'package:amap_flutter_map_example/const_config.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';

import 'package:amap_flutter_map/amap_flutter_map.dart';

class HarmonyMapDemoPage extends BasePage {
  HarmonyMapDemoPage(String title, String subTitle) : super(title, subTitle);

  @override
  Widget build(BuildContext context) {
    return _HarmonyMapDemoPageBody();
  }
}

class _HarmonyMapDemoPageBody extends StatefulWidget {
  @override
  State<StatefulWidget> createState() => _HarmonyMapDemoPageState();
}

class _HarmonyMapDemoPageState extends State<_HarmonyMapDemoPageBody> {
  List<Widget> _approvalNumberWidget = <Widget>[];
  String _initializationStatus = '检查中...';
  bool _isHarmonyPlatform = false;

  @override
  void initState() {
    super.initState();
    _checkHarmonyPlatform();
  }

  @override
  Widget build(BuildContext context) {
    final AMapWidget map = AMapWidget(
      apiKey: ConstConfig.amapApiKeys,
      onMapCreated: onMapCreated,
    );

    return ConstrainedBox(
      constraints: BoxConstraints.expand(),
      child: Stack(
        alignment: Alignment.center,
        children: [
          Container(
            height: MediaQuery.of(context).size.height,
            width: MediaQuery.of(context).size.width,
            child: map,
          ),
          // 鸿蒙平台状态信息
          Positioned(
            top: 50,
            left: 10,
            right: 10,
            child: Container(
              padding: EdgeInsets.all(12),
              decoration: BoxDecoration(
                color: Colors.white.withOpacity(0.9),
                borderRadius: BorderRadius.circular(8),
                boxShadow: [
                  BoxShadow(
                    color: Colors.black26,
                    blurRadius: 4,
                    offset: Offset(0, 2),
                  ),
                ],
              ),
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  Text(
                    '鸿蒙平台地图演示',
                    style: TextStyle(
                      fontSize: 16,
                      fontWeight: FontWeight.bold,
                      color: Colors.black87,
                    ),
                  ),
                  SizedBox(height: 8),
                  Text(
                    '平台检测: ${_isHarmonyPlatform ? "鸿蒙平台" : "其他平台"}',
                    style: TextStyle(fontSize: 14, color: Colors.black54),
                  ),
                  Text(
                    '初始化状态: $_initializationStatus',
                    style: TextStyle(fontSize: 14, color: Colors.black54),
                  ),
                  Text(
                    'API Key: 自动从 AMapApiKey.ohosKey 获取',
                    style: TextStyle(fontSize: 12, color: Colors.green),
                  ),
                  SizedBox(height: 8),
                  Row(
                    children: [
                      ElevatedButton(
                        onPressed: _checkInitializationStatus,
                        child: Text('检查状态'),
                        style: ElevatedButton.styleFrom(
                          backgroundColor: Colors.blue,
                          foregroundColor: Colors.white,
                        ),
                      ),
                      SizedBox(width: 8),
                      ElevatedButton(
                        onPressed: _ensureInitialized,
                        child: Text('确保初始化'),
                        style: ElevatedButton.styleFrom(
                          backgroundColor: Colors.green,
                          foregroundColor: Colors.white,
                        ),
                      ),
                    ],
                  ),
                ],
              ),
            ),
          ),
          // 审图号信息
          Positioned(
            right: 10,
            bottom: 15,
            child: Container(
              alignment: Alignment.centerLeft,
              child: Column(
                mainAxisAlignment: MainAxisAlignment.start,
                children: _approvalNumberWidget,
              ),
            ),
          ),
        ],
      ),
    );
  }

  late AMapController _mapController;

  void onMapCreated(AMapController controller) {
    setState(() {
      _mapController = controller;
      getApprovalNumber();
    });
  }

  /// 检查是否是鸿蒙平台
  Future<void> _checkHarmonyPlatform() async {
    try {
      const platform = MethodChannel('amap_flutter_map');

      // 尝试调用鸿蒙特有的方法
      final result = await platform.invokeMethod('getInitializationInfo');

      setState(() {
        _isHarmonyPlatform = true;
        _initializationStatus = '已连接到鸿蒙插件';
      });

      print('鸿蒙平台检测成功: $result');
    } catch (e) {
      setState(() {
        _isHarmonyPlatform = false;
        _initializationStatus = '非鸿蒙平台或插件未就绪';
      });

      print('平台检测: $e');
    }
  }

  /// 检查初始化状态
  Future<void> _checkInitializationStatus() async {
    try {
      const platform = MethodChannel('amap_flutter_map');
      final result = await platform.invokeMethod('getInitializationInfo');
      print(result.toString());
      setState(() {
        _initializationStatus = '状态已更新';
      });

      // 显示详细信息
      showDialog(
        context: context,
        builder: (context) => AlertDialog(
          title: Text('初始化状态'),
          content: Text(result.toString()),
          actions: [
            TextButton(
              onPressed: () => Navigator.of(context).pop(),
              child: Text('确定'),
            ),
          ],
        ),
      );

      print('初始化状态: $result');
    } catch (e) {
      setState(() {
        _initializationStatus = '状态检查失败';
      });
      print('状态检查失败: $e');
      ScaffoldMessenger.of(context).showSnackBar(
        SnackBar(content: Text('状态检查失败: $e')),
      );
    }
  }

  /// 确保初始化
  Future<void> _ensureInitialized() async {
    try {
      const platform = MethodChannel('amap_flutter_map');
      final result = await platform.invokeMethod('ensureInitialized');
      print(result.toString());
      setState(() {
        _initializationStatus = result ? '初始化成功' : '初始化失败';
      });

      ScaffoldMessenger.of(context).showSnackBar(
        SnackBar(
          content: Text(result ? '地图SDK初始化成功' : '地图SDK初始化失败'),
          backgroundColor: result ? Colors.green : Colors.red,
        ),
      );

      print('确保初始化结果: $result');
    } catch (e) {
      setState(() {
        _initializationStatus = '初始化调用失败';
      });
      print('初始化失败: $e');
      ScaffoldMessenger.of(context).showSnackBar(
        SnackBar(content: Text('初始化失败: $e')),
      );
    }
  }

  /// 获取审图号
  void getApprovalNumber() async {
    try {
      // 普通地图审图号
      String mapContentApprovalNumber =
          (await _mapController.getMapContentApprovalNumber())!;
      // 卫星地图审图号
      String satelliteImageApprovalNumber =
          (await _mapController.getSatelliteImageApprovalNumber())!;

      setState(() {
        _approvalNumberWidget.add(Text(
          mapContentApprovalNumber,
          style: TextStyle(fontSize: 10, color: Colors.black54),
        ));
        _approvalNumberWidget.add(Text(
          satelliteImageApprovalNumber,
          style: TextStyle(fontSize: 10, color: Colors.black54),
        ));
      });

      print('地图审图号（普通地图）: $mapContentApprovalNumber');
      print('地图审图号（卫星地图): $satelliteImageApprovalNumber');
    } catch (e) {
      print('获取审图号失败: $e');
    }
  }
}
